//
//  QCWebViewController.m
//  QCAppProject
//
//  Created by yjl on 2021/8/20.
//

#import "QCWebViewController.h"
#import <WebKit/WebKit.h>
#import "WeakWebViewScriptMessageDelegate.h"
#import "YFHUtil.h"

@interface QCWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>


@property(nonatomic,strong)WKWebView *webView;

@property(nonatomic,strong)NSString *linkUrl;

@end

@implementation QCWebViewController

//-(instancetype) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//
//    WKWebView *wk = [[WKWebView alloc] init];
//    [wk evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
//        NSString *userAgent = result;
//        NSArray *stringArray = [userAgent componentsSeparatedByString:@" "];
//        if ([stringArray containsObject:@"fdd_authentication_ios_v3"]) {
//            return;
//        }
//        NSString *newUserAgent = [userAgent stringByAppendingString:@"fdd_authentication_ios_v3"];
//        NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
//        [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//        [wk setCustomUserAgent:newUserAgent];
//    }];
//    return  self;
// }


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

-(void)setupUI{
    if (self.queryLinkType == QCQueryLinkFefu) {
        self.title = @"在线客服";
    } else {
        self.title = @"查询服务";
    }
    self.linkUrl = self.url;
    CGFloat webHeight = [UIScreen mainScreen].bounds.size.height - kTopBarHeight;
    if ([YFHUtil isBlankString:self.url]) {
        webHeight = [UIScreen mainScreen].bounds.size.height - kTopBarHeight - kTabBarHeight;
        self.linkUrl = [[NSUserDefaults standardUserDefaults] objectForKey:kQueryLinkKey];
    }
    [self.view addSubview:self.webView];
    self.webView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, webHeight);
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.linkUrl]]];
}

#pragma mark ----WKWebViewDwelegate,管理滑动返回
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{

}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{

}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
//    [QCProgressHUD hideHUD];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{

}
// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{

}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
}

// 在发送请求之前，决定是否跳转

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    QCLog(@"decisionHandler ---- %@", navigationAction.request.URL.absoluteString)
    NSString*urlString = navigationAction.request.URL.absoluteString;
    urlString = [urlString stringByRemovingPercentEncoding];
    NSURLRequest *request        = navigationAction.request;
    NSString     *scheme         = [request.URL scheme];
    
    if (![scheme isEqualToString:@"https"] && ![scheme isEqualToString:@"http"]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        NSURL *requestURL = request.URL;
        if ([@"weixin" isEqualToString:scheme]) {
//            NSString *endPayRedirectURL = urlString;
//            if (endPayRedirectURL) {
//                [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:endPayRedirectURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]];
//                endPayRedirectURL = nil;
//            }
        } else if ([@"alipay" isEqualToString:scheme]) {
            /*
             替换里面的默认Scheme为自己的Scheme LGKJAliPay
             在Info.plist 增加对应的URLTypes LGKJAliPay
             */
            NSArray *urlBaseArr = [navigationAction.request.URL.absoluteString componentsSeparatedByString:@"?"];
            NSString *urlBaseStr = urlBaseArr.firstObject;
            NSString *urlNeedDecode = urlBaseArr.lastObject;
            NSMutableString *afterDecodeStr = [NSMutableString stringWithString:[urlNeedDecode stringByRemovingPercentEncoding]];
            NSString *afterHandleStr = [afterDecodeStr stringByReplacingOccurrencesOfString:@"alipays" withString:@"alipay"];
            NSString *finalStr = [NSString stringWithFormat:@"%@?%@",urlBaseStr, [self encodeString:afterHandleStr]];
            requestURL = [NSURL URLWithString:finalStr];
        }
        BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:requestURL];
        QCLog(@"canOpen Url %@ = %@", @(canOpen), requestURL.description)
        if (canOpen) {
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:requestURL
                                                   options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO}
                                         completionHandler:^(BOOL success) {
                }];
            } else {
                // Fallback on earlier versions
            }
        }
        
        return;
    }

    decisionHandler(WKNavigationActionPolicyAllow);
}

- (NSString*)encodeString:(NSString*)unencodedString {
    if([[[UIDevice currentDevice]systemVersion]floatValue] >=9.0) {
        return [unencodedString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];
        
    }
    NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";//#%<>[\]^`{|} //@"!*'();:@&=+$,/?%#[]"
    NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
    NSString *encodedString = [unencodedString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
    return encodedString;
}


//- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//    QCLog(@"decisionHandler ---- %@", navigationAction.request.URL.absoluteString)
//    NSString*urlString = navigationAction.request.URL.absoluteString;
//    urlString = [urlString stringByRemovingPercentEncoding];
//    NSURLRequest *request        = navigationAction.request;
//    NSString     *scheme         = [request.URL scheme];
//
//    if (![scheme isEqualToString:@"https"] && ![scheme isEqualToString:@"http"]) {
//        decisionHandler(WKNavigationActionPolicyCancel);
//        NSURL *requestURL = request.URL;
//        if ([@"weixin" isEqualToString:scheme]) {
//            if (endPayRedirectURL) {
//                [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:endPayRedirectURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]];
//                endPayRedirectURL = nil;
//            }
//        } else if ([@"alipay" isEqualToString:scheme]) {
//            /*
//             替换里面的默认Scheme为自己的Scheme LGKJAliPay
//             在Info.plist 增加对应的URLTypes LGKJAliPay
//             */
////            NSArray *urlBaseArr = [navigationAction.request.URL.absoluteString componentsSeparatedByString:@"?"];
////            NSString *urlBaseStr = urlBaseArr.firstObject;
////            NSString *urlNeedDecode = urlBaseArr.lastObject;
////            NSMutableString *afterDecodeStr = [NSMutableString stringWithString:[urlNeedDecode  stringDecoderUrlEncode]];
////            NSString *afterHandleStr = [afterDecodeStr stringByReplacingOccurrencesOfString:@"alipays" withString:@"LGKJAliPay"];
////            NSString *finalStr = [NSString stringWithFormat:@"%@?%@",urlBaseStr, [afterHandleStr stringUrlEncode]];
////            requestURL = [NSURL URLWithString:finalStr];
//        }
//        BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:requestURL];
//        QCLog(@"canOpen Url %@ = %@", @(canOpen), requestURL.description)
//        if (canOpen) {
//            if (@available(iOS 10.0, *)) {
//                [[UIApplication sharedApplication] openURL:requestURL
//                                                   options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO}
//                                         completionHandler:^(BOOL success) {
//                }];
//            } else {
//                // Fallback on earlier versions
//            }
//        }
//        return;
//    }
//
//    decisionHandler(WKNavigationActionPolicyAllow);
//}


-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
   
   UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
   [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
       completionHandler();
   }]];
   
   [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark =======WKScriptMessageHandler=========

//被自定义的WKScriptMessageHandler在回调方法里通过代理回调回来，绕了一圈就是为了解决内存不释放的问题
//通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    //用message.body获得JS传出的参数体
//    if([message.name isEqualToString:@"goHome"]){
//        [self requestCompanyStatusWithCompanyID];
//    }
}

#pragma  mark ----js和oc相互调用
- (WKWebView *)webView{
    if(_webView == nil){
        //创建网页配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];

        //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
//        WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
        //这个类主要用来做native与JavaScript的交互管理

        WKUserContentController * wkUController = [[WKUserContentController alloc] init];
        //注册一个name为jsToOcNoPrams的js方法 设置处理接收JS方法的对象
//         [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"goHome"];
        config.userContentController = wkUController;

        // 初始化wkview
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        _webView.navigationDelegate = self;
        //开启网页滑动返回功能
        _webView.allowsBackForwardNavigationGestures = YES;
    }
    return _webView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
